package com.cooper.mediadb.online;

import java.util.ArrayList;
import java.util.List;

import com.cooper.android.comm.DataChangedListener;
import com.cooper.mediadb.Mark;
import com.cooper.mediadb.Media;
import com.cooper.mediadb.MediaBrowseBaseFragment;
import com.cooper.mediadb.download.MovieDownResAdapter;
import com.cooper.resource.download.DownloadResource;
import com.cooper.resource.download.DownloadServiceMgr;
import com.cooper.scrapemedialib.R;
import com.cooper.scraper.RunnerSubscribe;
import com.cooper.scraper.show.FanartViewStrategy;
import com.cooper.scraper.show.OnlineFanartViewStrategy;
import com.cooper.scraper.show.ResourceCommandAction;

import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.widget.Toast;

public abstract class OnlineMediaFragment extends
		MediaBrowseBaseFragment<OnlineMedia> implements
		MediaSrcSelectDialog.MediaSrcSelectedListener, DataChangedListener,
		RunnerSubscribe {

	// private static final int AD_VIEW_ID = 500;

	// protected View noResultMessage;

	@Override
	public void onPause() {
		super.onPause();
		OnlineMediaScrapeRunner.getInstance().cancelSubscribe(this);
		dismissFullWaitingDialog();
	}

	@Override
	public void onResume() {
		super.onResume();
		Log.d("OnlineMediaFragment", "call Fragment onResume:" + this);
		OnlineMediaScrapeRunner.getInstance().subscribe(this);
		switchMediaViewShow();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d("OnlineMediaFragment", "Fragment call onDestroy:" + this);


	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		if (viewStrategy != null) {
			viewStrategy.destroy();
			viewStrategy = null;
		}
	}

	@Override
	public void onMediaSelected(OnlineMedia media) {
	}

	@Override
	public boolean onMediaClick(OnlineMedia media) {
		return false;
	}

	@Override
	public void onFullWatingCanceled() {
		if (playStep > 0) {
			if (playStep == 1) {
				currentMedia.cancelDetails();
			} else if (playStep == 2) {
				OnlineMediaScrapeRunner.getInstance().cancel(this);
				playSource = null;
			}
			playStep = 0;
		}
	}

	public void onSelectPlayMedia(boolean continued) {
		if (continued) {
			MediaSource markSource = currentMedia.getSourceBySrc(useMark
					.getType());
			if (markSource != null) {
				mediaSrcSelected(markSource);
				return;
			}
		}
		mediaSrcSelect();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// getResources().getConfiguration().orientation ==
		// Configuration.ORIENTATION_PORTRAIT

		// calcFanartSize(newConfig);
		// fanartsViewShow.configurationChanged(newConfig, getWindowManager()
		// .getDefaultDisplay());
	}

	private OnlineFanartViewStrategy<OnlineMedia> viewStrategy = null;

	@Override
	protected FanartViewStrategy<OnlineMedia> getViewStrategy() {
		if (viewStrategy == null) {
			viewStrategy = new OnlineFanartViewStrategy<OnlineMedia>(this
					.getActivity().getApplicationContext(),
					OnlineMediaScrapeRunner.getInstance());
		}
		return viewStrategy;
	}

	@Override
	protected void playMedia(OnlineMedia media) {
		playFor = MediaSrcMgr.GET_SOURCE_BY_PLAY;
		analyzeMedia(media);
	}

	@Override
	protected void initCommandAction() {
		super.initCommandAction();

		if (canDownload()) {
			ResourceCommandAction<OnlineMedia> actionCommand = new ResourceCommandAction<OnlineMedia>() {
				@Override
				public void execute(OnlineMedia media) {
					playFor = MediaSrcMgr.GET_SOURCE_BY_DOWNLOAD;
					analyzeMedia(media);
				}
			};
			actionCommand.setGroup(0);
			actionCommand.setIconResId(R.drawable.ic_down);
			actionCommand.setTitle(getResources().getString(
					R.string.media_menu_down));
			commands.add(actionCommand);
		}

	}

	protected abstract boolean canDownload();

	protected abstract Mark.MarkDao getMarkDao();

	protected abstract MediaSrcSelectDialog createMediaSrcSelectDialog(
			int sourceFor);

	private int playStep = 0;
	// private boolean playForDownload;
	protected int playFor = MediaSrcMgr.GET_SOURCE_BY_PLAY;
	private Mark useMark = null;

	private void mediaSrcSelect() {
		useMark = null;
		List<MediaSource> movieSources = currentMedia.getSources(playFor);
		if (movieSources == null || movieSources.isEmpty()) {
			Toast.makeText(getActivity().getApplicationContext(),
					R.string.media_source_analyze_fial, Toast.LENGTH_LONG)
					.show();
			playSource = null;
			playStep = 0;
		} else if (movieSources.size() == 1) {
			mediaSrcSelected(movieSources.get(0));
		} else {
			createMediaSrcSelectDialog(playFor).show(
					getActivity().getSupportFragmentManager(),
					"MEDIA_SRC_SELECT_DIALOG");
		}
	}

	protected void analyzeMedia(OnlineMedia media) {
		currentMedia = media;
		if (media.detailsIsReady()) {
			Mark mark;
			if (playFor != MediaSrcMgr.GET_SOURCE_BY_PLAY) {
				mark = null;
			} else {
				mark = getMarkDao().getMark(media.getId());
			}
			if (mark != null
					&& MediaSrcMgr.getInstance().containsSrc(
							media.getPlayListUrl().keySet(), mark.getType())) {
				useMark = mark;
				showContinuePlayMediaDialog();
			} else
				mediaSrcSelect();
		} else {
			playStep = 1;
			showFullWaitingDialog(R.string.analyze_movie_details, true);

			media.setDetailsReadyListener(this);
			media.prepareDetails(getActivity().getApplicationContext());
		}
	}

	// private String playUrl = null;
	// private int playSrc = -1;
	private MediaSource playSource = null;

	private String getMediaDefaultFormat() {
		SharedPreferences p = PreferenceManager
				.getDefaultSharedPreferences(getActivity());
		return p.getString("preferenace_media_format", "normal");
	}

	@Override
	public void mediaSrcSelected(MediaSource source) {
		if (playFor == MediaSrcMgr.GET_SOURCE_BY_DOWNLOAD) {
			playSource = null;
			playStep = 0;

			DownloadResource requestRes = new MovieDownResAdapter(currentMedia,
					source, getMediaDefaultFormat());

			Toast.makeText(
					getActivity(),
					((DownloadServiceMgr) getActivity())
							.getDownloadServerBinder()
							.addToDownload(requestRes), Toast.LENGTH_LONG)
					.show();

		} else {
			playSource = source;
			playStep = 2;

			if (playSource.getSrc() == MediaSrcMgr.SRC_UNKNOW) {
				List<String> urls = new ArrayList<String>();
				urls.add(playSource.getUrl());
				playRealMedia(urls);
			} else {
				showFullWaitingDialog(R.string.analyze_movie_details, true);

				OnlineMediaScrapeRunner.getInstance().analyzeMediaUrl(getActivity(), playSource,
						getMediaDefaultFormat());
			}
		}

	}

	@Override
	public void onMediaPlayResult(Uri uri, int position) {
		Log.d("OnlineMoviesActivity", "save mark:" + uri + "-" + position);
		if (uri != null) {
			if (playingUris != null) {
				getMarkDao().insertMark(currentMedia.getId(),
						playSource.getSrc(),
						String.valueOf(playingUris.indexOf(uri)), position);
			} else {
				getMarkDao().insertMark(currentMedia.getId(),
						playSource.getSrc(), uri.toString(), position);
			}
		}
		playSource = null;
		playingUris = null;
	}

	@Override
	public void onNotifyDataChanged(Object sender, int what, Object data) {
		dismissFullWaitingDialog();
		currentMedia.setDetailsReadyListener(null);
		if (what == Media.DETAILS_IS_OK) {
			analyzeMedia((OnlineMedia) sender);
		} else {
			Toast.makeText(getActivity(), R.string.down_movie_details_fail,
					Toast.LENGTH_LONG).show();
		}
	}

	private List<Uri> playingUris = null;

	@Override
	public void onDownloadComplete(String key, Object data) {
		dismissFullWaitingDialog();
		@SuppressWarnings("unchecked")
		List<String> playList = (List<String>) data;
		playRealMedia(playList);
	}

	protected void onMediaSourcesGeted(OnlineMedia media, List<Uri> uris) {

	}

	private void playRealMedia(List<String> playList) {
		if (playList.isEmpty()) {
			playSource = null;
			Toast.makeText(getActivity(), R.string.media_source_analyze_fial,
					Toast.LENGTH_LONG).show();
		} else {
			playingUris = new ArrayList<Uri>();
			for (String s : playList) {
				Log.d("OnlineMoviesActivity", "id:" + currentMedia.getId()
						+ "|uri:" + s);
				if ((s != null) && (!"".equals(s)))
					playingUris.add(Uri.parse(s));
			}
			playStep = 0;
			if (playFor == MediaSrcMgr.GET_SOURCE_ALL) {
				onMediaSourcesGeted(currentMedia, playingUris);
			} else {
				if (useMark != null) {
					Uri markUri;
					try {
						markUri = playingUris.get(Integer.parseInt(useMark
								.getUri()));
					} catch (Exception e) {
						try {
							markUri = Uri.parse(useMark.getUri());
						} catch (Exception e1) {
							markUri = null;
						}
					}

					if (markUri == null || !playingUris.contains(markUri)) {
						Log.w("OnlineMoviesActivity", "mark uri not contains");
						playMedia(playingUris, currentMedia.getTitle());
					} else {
						playMedia(playingUris, currentMedia.getTitle(),
								markUri, useMark.getPosition());
					}
					useMark = null;
				} else
					playMedia(playingUris, currentMedia.getTitle());
			}
		}
	}

	@Override
	public void onDownloadFail(String key, int errorCode) {
		playStep = 0;
		dismissFullWaitingDialog();
		Toast.makeText(getActivity(), R.string.media_source_analyze_fial,
				Toast.LENGTH_LONG).show();
		playSource = null;
	}

	@Override
	public void onDownloadCancel(String key) {
	}

	@Override
	protected void showMovieDetails(OnlineMedia media) {
		currentMedia = media;
		OnlineMediaInfoDialog mediaInfoDialog = new OnlineMediaInfoDialog();
		FragmentManager fm = getActivity().getSupportFragmentManager();
		mediaInfoDialog.show(fm, "MEDIA_INFO_DIALOG");
	}

	@Override
	public boolean subscribed(String key) {
		if (playSource != null) {
			return playSource.getUrl().equals(key);
		} else
			return false;
	}

}
